package com.oocl.aeat.listener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;

import com.oocl.aeat.pojo.Verify;
import com.oocl.aeat.service.VerifyService;
import com.oocl.aeat.util.Base64Util;
import com.oocl.aeat.util.JsonUtil;
import com.oocl.aeat.util.ServerConfig;

public class JMSConsumerListener implements MessageListener{
	private Logger logger = Logger.getLogger(JMSConsumerListener.class);
	private String rootPath;
	private VerifyService vs;
	private static final String IDCARD = "/aeat/images/idcard/";
	private static final String MUSER = "/aeat/images/muser/";
	
	public JMSConsumerListener(VerifyService vs, String rootPath) {
		this.rootPath=rootPath;
		this.vs=vs;
	}

	@Override
	public void onMessage(Message message) {
		try {
			String text = ((TextMessage)message).getText();
			Verify dto = JsonUtil.getObjectFromJson(text, Verify.class);
			String uuid = dto.getMid();
			Date d = new Date();
			SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd_HHmmss");
			String dateStr = sdf.format(d);
			String fileName = uuid + "_" + dateStr + ".png";
			//IO
			byte[] muserByte = Base64Util.base64ToByte(dto.getImg());
			byte[] idcardByte = Base64Util.base64ToByte(dto.getIdcard());
			
			String muserFileName = rootPath + MUSER + fileName;
			String idcardFileName = rootPath + IDCARD + fileName;

			System.out.println(muserFileName);
			System.out.println(idcardFileName);
			
			File tmp1 = new File(muserFileName);
			File tmp2 = new File(idcardFileName);
			if(!tmp1.exists()){
				tmp1.createNewFile();
			}
			if(!tmp2.exists()){
				tmp2.createNewFile();
			}
			
			FileOutputStream muserFos = new FileOutputStream(muserFileName);
			muserFos.write(muserByte);
			muserFos.flush();
			muserFos.close();
			
			FileOutputStream idcardFos = new FileOutputStream(idcardFileName);
			idcardFos.write(idcardByte);
			idcardFos.flush();
			idcardFos.close();

			dto.setBlock(0);
			dto.setState(0);
			dto.setImg(ServerConfig.NGINX_IMAGE_URL+ MUSER + fileName);
			dto.setIdcard(ServerConfig.NGINX_IMAGE_URL+ IDCARD + fileName);

			System.out.println( dto.toString() );
			
			boolean b =vs.addVerify(dto);
			if(b){
				logger.info("id="+dto.getMid()+" add verify success.");
			}else{
				logger.info("id="+dto.getMid()+" add verify failure.");
			}
			message.acknowledge();
		} catch (JMSException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}
